package net.sahv.bdyz.util;

import java.util.Calendar;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 初始化站点信息的监听器
 * @author 马亚民
 * @version 1.0(2016-02-04)
 */
public class AppListener implements HttpSessionListener,ServletContextListener,ServletRequestListener{
	private ServletContext sc;
	//private Map<String,Date> activeSessions=new HashMap<String,Date>();//存放当前在线的session 和过期时间
	private int sessionCount=0; //独立会话数量缓存
	private Calendar cal=Calendar.getInstance();

	/**
	 * 系统启动时初始化存放当前在线session的集合
	 * @param sce ServletContextEvent
	 * @return void
	 */
	public void contextInitialized(ServletContextEvent sce){
		sc=sce.getServletContext();
		//sc.setAttribute("activeSessions",activeSessions);
		sc.setAttribute("sessionCount",sessionCount);
		this.initSetup();
	}

	/**
	 * 系统关闭时，将未保存的信息保存到数据库
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		//SiteAnalyzeService.updateCount("update SiteCount set session=session+"+this.getSessionCount()+" where countDate='"+DateUtils.getFormatDate(cal.getTime(), "yyyy-MM-dd")+"'");
	}

	/**
	 * 开始一个会话时保存相关信息
	 */
	public void sessionCreated(HttpSessionEvent se) {

	}

	/**
	 * 会话结束时保存相前信息
	 */
	public void sessionDestroyed(HttpSessionEvent se) {
		  //if(this.activeSessions.containsKey(se.getSession().getId())){
			  //SiteAnalyzeService.deleteSessionId(se.getSession().getId());
			  //this.activeSessions.remove(se.getSession().getId());
		  //
	}
	
	/**
	 * 开始一个新请求时执行
	 */
	  public void requestInitialized(ServletRequestEvent sre){
		 /* HttpServletRequest request=(HttpServletRequest)sre.getServletRequest();
		  HttpSession session=request.getSession();
		  if(session.getAttribute("cityInfo")==null){
			  //如果没有ip信息，则初始化ip信息
			  IIPAdressService ipaddressService=(IIPAdressService)SpringUtils.getBean("ipService");
			  IAreaCodeService areaService=(IAreaCodeService)SpringUtils.getBean("areaCodeService");
			  CityInfo ci=new CityInfo();
			  String ip=ipaddressService.getIpAddr(request);
			  //String ip="222.222.28.22";
			  log(ip);//统计信息
			  ci.setIpAddress(ip);
			  String[] area=ipaddressService.transIPAdderss(ip);
			  ci.setFullName(area[0]+area[1]);
			  
			  AreaCode ac=areaService.getCityAreaCode(area[0]);
			  if(ac!=null){
				  ci.setCountyCode(ac.getAreaCode());
				  ci.setCountyName(area[0]);
				  String cityCode=ac.getAreaCode().substring(0,4);
				  ci.setCityCode(cityCode+"00");
				  ci.setCityName(areaService.getCityName(cityCode+"00"));
				  //判断是否是南网各地市
				  if("1301".equals(cityCode)||
						  "1304".equals(cityCode)||
						  "1305".equals(cityCode)||
						  "1306".equals(cityCode)||
						  "1309".equals(cityCode)||
						  "1311".equals(cityCode)){
					  ci.setSelectedCity(cityCode+"00");
				  }
				  else{
					  //默认为河北省
					  ci.setSelectedCity("130000");
				  }
			  }
			  else{
				  //不是河北省的显示实际登录所在地
				  ci.setCityCode("");
				  //String tmp=area[0].replaceAll("(.+省)?(.+?市).*","$2");
				  ci.setCityName(area[0]);
				  ci.setCountyName(area[0]);
				  //默认为河北省
				  ci.setSelectedCity("130000");
			  }
			  session.setAttribute("cityInfo",ci);
		  }*/
		  /*
		  if(!WebGlobal.requestInited){
			  HttpServletRequest request=(HttpServletRequest)sre.getServletRequest();
			  if("".equals(WebGlobal.contextPath)){
				  WebGlobal.contextPath=request.getContextPath();
			  }
			  if("".equals(WebGlobal.domain)){
				  WebGlobal.domain=request.getRequestURL().toString();
				  WebGlobal.domain=WebGlobal.domain.substring(0,WebGlobal.domain.indexOf('/',10));
			  }
			  if(WebGlobal.indexStaticSetup==null){
				  WebGlobal.indexStaticSetup=StaticPageService.getStaticSetup(1);
				  this.startIndexTimer((StaticSetup)WebGlobal.indexStaticSetup);
			  }
			  if(WebGlobal.listStaticSetup==null){
				  WebGlobal.listStaticSetup=StaticPageService.getStaticSetup(2);
				  this.startListTimer((StaticSetup)WebGlobal.listStaticSetup);
			  }
			  if(WebGlobal.sideStaticSetup==null){
				  WebGlobal.sideStaticSetup=StaticPageService.getStaticSetup(3);
				  this.startListTimer((StaticSetup)WebGlobal.sideStaticSetup);
			  }
			  WebGlobal.requestInited=true;
		  }
		  */
	  }
	  
	  //保存统计数据  
	  private void log(String ip) {
//			HttpServletRequest req = (HttpServletRequest) ServletActionContext
//			.getRequest();
//			String visitorIp = req.getHeader("x-forwarded-for");
//			if (visitorIp == null || visitorIp.length() == 0 || "unknown".equalsIgnoreCase(visitorIp)) {
//				visitorIp = req.getHeader("Proxy-Client-IP");
//			}
//			if (visitorIp == null || visitorIp.length() == 0 || "unknown".equalsIgnoreCase(visitorIp)) {
//				visitorIp = req.getHeader("WL-Proxy-Client-IP");
//			}
//			if (visitorIp == null || visitorIp.length() == 0 || "unknown".equalsIgnoreCase(visitorIp)) {
//				visitorIp = req.getRemoteAddr();
//			}
//			String visitorhost = req.getRemoteHost();
//			int visitorPort = req.getRemotePort();
//			String visitorUsername = req.getRemoteUser();
//			String visitorUrl = req.getRequestURI();
//
//			System.out.println("访问者的ip是" + visitorIp);
//			System.out.println("访问者的主机名是" + visitorhost);
//			System.out.println("访问者的访问端口是" + visitorPort);
//			System.out.println("访问者的用户名是" + visitorUsername);
//			System.out.println("访问者的url是" + visitorUrl);
//
//			SiteCount siteCount = new SiteCount(null,ip);
//			ISiteCountService siteCountService=(ISiteCountService)SpringUtils.getBean("SiteCountService");
//			siteCountService.addSiteCount(siteCount);
	}

	/**
	   * 初始华系统配置，原来在系统启动时进行，但如果数据库有错，可能会出错。
	   */
	  public void initSetup(){
		  //如果还没有初使化，则进行初始化,在第一次使用时获取系统设置
		if (sc.getAttribute("setup") == null) {
			try{
				WebGlobal.realPath=sc.getRealPath("/");
				WebGlobal.contextPath=sc.getContextPath();
				WebGlobal.LoadMenuCheck=Boolean.parseBoolean(sc.getInitParameter("LoadMenuCheck"));
				WebGlobal.SendSMS=Boolean.parseBoolean(sc.getInitParameter("SendSMS"));
				sc.setAttribute("setup","1");
			}
			catch(Exception e){
				e.printStackTrace();
				sc.removeAttribute("setup");
			}
		}
	  }

	/**
	 * 结束一个请求时执行
	 */
	public void requestDestroyed(ServletRequestEvent sre) {

	}

	public int getSessionCount() {
		this.sessionCount=(Integer)sc.getAttribute("sessionCount");
		return this.sessionCount;
	}

	public void setSessionCount(int sessionCount) {
		this.sessionCount = sessionCount;
		sc.setAttribute("sessionCount",sessionCount);
	}
}
